// 引入模块
const KoaRouter = require('koa-router')
// 实例化
const router = new KoaRouter();

const { User } = require('../database/index')
const { getToken, verify } = require('../middleware/koa-jwt')

//自动添加前缀
router.prefix('/login');

router
  // 用户登录
  .post('/', async (ctx) =>{
    console.log('登录')
    let { username, password } = ctx.request.body;
    // 校验该用户， 返回一个数组
    let user = await User.find({
        username
    })

    if(user){
        // 校验成功
        if(user[0].password === password){
            //生成token
            let token = getToken({
                name: user[0].name
            })
            console.log('生成token: ', token)
            ctx.response.body = {
                msg: '登录成功',
                token,
                code: 20000
            }
        }else{
            ctx.response.body = {
                msg: '密码错误',
                code: 40003
            }
        }
    }else{
        ctx.response.body = {
            msg: '用户名不存在',
            code: 40003
        }
    }
  })
  // 用户注册
  .post('/register', async (ctx) =>{
    console.log('注册')
    let { username, password, name, sex, phone, email} = ctx.request.body

    console.log( username,name)

    // 新建用户信息
    let user = new User({
        username,
        password,
        name,
        sex,
        phone,
        email
    })

    // 保存
    await user.save();

    //返回状态码
    ctx.response.status = 200
    //响应体
    ctx.response.body = {
      msg: '添加成功!',
      code: '20000'
    }
  })
  //登出
  .get('/logout', async (ctx) =>{
    ctx.body = {
      msg: '登出'
    }
  })
  //获取用户信息
  .get('/userinfo', async ctx =>{
    let token = (ctx.request.querystring).match(/(?:=)[^]*/)[0].slice(1)
    // console.log('userinfo token:',token)
    let { name } = verify(token);

    let userInfo = await User.find({
      name
    }).select('-password -_id') 

    ctx.response.body = {
      userInfo,
      code: 20000
    }
  })

module.exports.loginRouter = router